package com.atgugu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atgugu.realtime.app.BaseAppV1;
import com.atgugu.realtime.common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/28 9:18
 */
public class DwmUserJumpDetailApp extends BaseAppV1 {
    public static void main(String[] args) {
        new DwmUserJumpDetailApp().init(3002, 1, "DwmUserJumpDetailApp", "DwmUserJumpDetailApp", Constant.TOPIC_DWD_PAGE);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        stream =
            env.fromElements(
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":11000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":12000}",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"home\"},\"ts\":14000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"detail\"},\"ts\":50000} "
            );
        
        KeyedStream<JSONObject, String> keyedStream = stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((page, ts) -> page.getLong("ts"))
            )
            .keyBy(page -> page.getJSONObject("common").getString("mid"));
        
        // 1. 定义模式
        // a: 入口 b:紧跟着一个其他的页面
        Pattern<JSONObject, JSONObject> pattern = Pattern
            .<JSONObject>begin("entry")
            .where(new SimpleCondition<JSONObject>() {  // 入口
                @Override
                public boolean filter(JSONObject value) throws Exception {
                    String lastPageId = value.getJSONObject("page").getString("last_page_id");
                    return lastPageId == null || lastPageId.length() == 0;
                }
            })
            .next("normal")
            .where(new SimpleCondition<JSONObject>() { // 非入口
                @Override
                public boolean filter(JSONObject value) throws Exception {
                    String lastPageId = value.getJSONObject("page").getString("last_page_id");
                    return lastPageId != null && lastPageId.length() > 0;
                    
                }
            })
            .within(Time.seconds(5));
        
        // 2. 把模式作用在流上
        PatternStream<JSONObject> ps = CEP.pattern(keyedStream, pattern);
        
        // 3. 从模式流取出匹配到的数据(超时数据)
        SingleOutputStreamOperator<JSONObject> normal = ps.select(
            new OutputTag<JSONObject>("uj") {},
            new PatternTimeoutFunction<JSONObject, JSONObject>() {
                @Override
                public JSONObject timeout(Map<String, List<JSONObject>> map,
                                          long timeoutTimestamp) throws Exception {
                    
                    return map.get("entry").get(0);
                }
            },
            new PatternSelectFunction<JSONObject, JSONObject>() {
                @Override
                public JSONObject select(Map<String, List<JSONObject>> pattern) throws Exception {
                    return null;
                }
            }
        );
        
        normal.getSideOutput(new OutputTag<JSONObject>("uj") {}).print("uj");
        
    }
}
